﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;

namespace TicTacToe
{
    public class CGame : IObserver
    {
        public static int boardSize = 3;
        static HashSet<int>[] win = new HashSet<int>[]{
            new HashSet<int>{1,4,7}, new HashSet<int>{2,5,8}, new HashSet<int>{3,6,9},
            new HashSet<int>{1,2,3}, new HashSet<int>{4,5,6}, new HashSet<int>{7,8,9},
            new HashSet<int>{1,5,9}, new HashSet<int>{3,5,7}
        };
        IPiece[,] chessBoard = null;
        IPiece lastPlayer = null;
        public IPiece Winner {
            get;
            private set;
        }
        IBoardPresenter bp;

        public String View{
            get {
                return bp.PresentBoard(this);
            }
        }
        public Boolean SetChessBoard(int x, int y, IPiece piece)
        {
            if (chessBoard[x, y] == null){
                chessBoard[x, y] = piece;
                lastPlayer = piece;
                return true;
            }
            return false;
        }

        public void Update(){
            if (WinnerCheck(lastPlayer))
            {
                Console.WriteLine(".....");
                Winner = lastPlayer;
            }
        }

        Boolean WinnerCheck(IPiece piece){
            var Collector = new HashSet<int>();
            for (int x = 0; x < boardSize; x++)
            {
                for (int y = 0; y < boardSize; y++)
                {
                    if (GetChessBoard(x, y).Equals(piece))
                    {
                        Collector.Add(pointToRaw(x, y));
                    }
                }
            }
            foreach(var w in win){
                if (Collector.IsSupersetOf(w)){
                    return true;
                }
            }
            return false;
        }

        public IPiece GetChessBoard(int x, int y){
            return chessBoard[x, y] == null ? new CNull() : chessBoard[x, y];
        }

        public CGame(IBoardPresenter b)
        {
            bp = b;
            chessBoard = new IPiece[boardSize, boardSize];
            Winner = null;
        }

        int pointToRaw(int x, int y){
            return x + 1 + (y * 3);
        }
    }
}
